<?php
include('AdminController.php');
include('simple_html_dom.php');
class SourceController extends AdminController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */


	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}


	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$rss = Rss::model()->findAll('source_id='.$id,array('order'=>'rss_updated_at DESC'));
		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'rss'=>$rss
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Source;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Source']))
		{
			$_POST['Source']['source_updated_at']=date('Y-m-d H:i:s');
			$_POST['Source']['source_created_at']=date('Y-m-d H:i:s');
			$model->attributes=$_POST['Source'];
			if($model->save())
				$this->redirect(array('index'));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Source']))
		{
			$_POST['Source']['source_updated_at']=date('Y-m-d H:i:s');
			$model->attributes=$_POST['Source'];
			if($model->save())
				$this->redirect(array('index'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$sources = Source::model()->findAll(array('order'=>'source_updated_at DESC'));
		$this->render('index',array(
			'sources'=>$sources,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Source('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Source']))
			$model->attributes=$_GET['Source'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

        
        public function actionGennews($id){
            if (isset($_POST['gen'])){
			$numOfNews = $_POST['gen']['quantity'];
			$rssID = $_POST['gen']['rss'];
			$rss = Rss::model()->find('rss_id='.$rssID);
			$source = Source::model()->findByPK($rss->source_id);
			$html = file_get_html($rss->rss_link);
			$items = $html->find('item');
			$len = 0;
			if(sizeof($items)<=$numOfNews) $len = sizeof($items);
			else $len = $numOfNews;
			for($i=0;$i<$len;$i++){
				$title = $items[$i]->find('title');
				$description = $items[$i]->find('description');
				$link = $items[$i]->find('link');
				$pub = $items[$i]->find('pubDate');
					
				if($pub[0]->innertext==''){
						preg_match_all("|<pub>(.*)</pub>|U",$items[$i],$out, PREG_SET_ORDER);
						$pub[0]= str_get_html($out[0][1]);
					}
				if($description[0]->innertext==''){
						preg_match_all("|<description>(.*)</description>|U",$items[$i],$out, PREG_SET_ORDER);
						$description[0]= str_get_html($out[0][1]);
					}
				if($title[0]->innertext==''){
						preg_match_all("|<title>(.*)</title>|U",$items[$i],$out, PREG_SET_ORDER);
						$title[0]= str_get_html($out[0][1]);
					}
				if($link[0]->innertext==''){
						preg_match_all("|<link>(.*)</link>|U",$items[$i],$out, PREG_SET_ORDER);
						$link[0] = str_get_html($out[0][1]);
					}
				
				
				$contents = file_get_html($link[0]->innertext);
				
				$content = $contents->find($source->source_selector);
				
				$model = new News;
				$model->news_title=$title[0]->innertext;
				$model->news_description = $description[0]->innertext;
				$model->news_content=$content[0];
				$model->news_created_at= date('Y-m-d H:i:s',strtotime($pub[0]->innertext));
				$model->news_updated_at= date('Y-m-d H:i:s',strtotime($pub[0]->innertext));
				$model->source_id	=$source->source_id;
				$model->category_id = $rss->category_id;
				$model->save();
				}
				exit(0);
			}
			else{
			$model = Rss::model()->findAll('source_id='.$id);
			$this->render('gennews',array('model'=>$model));
			}
		}
		
		//generate new 

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Source::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='source-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
